﻿using System;
using System.Text;

namespace Aks.Deployment.SharePoint.Data
{
	/// <summary>
	/// Represents a CAML order by node.
	/// </summary>
	internal class CamlOrderBy : CamlNode
	{
		/// <summary>CAML order by clause. Arguments include: (0) XML comparisons.</summary>
		internal const string CamlFormat = @"<OrderBy>{0}</OrderBy>";


		/// <summary>
		/// Initializes a new instance of the <see cref="CamlOrderBy"/> class.
		/// </summary>
		public CamlOrderBy()
		{}


		/// <summary>
		/// Initializes a new instance of the <see cref="CamlOrderBy"/> class.
		/// </summary>
		/// <param name="fields">The fields.</param>
		public CamlOrderBy(params string[] fields)
		{
			if (fields == null)
				return;
			Fields = new CamlOrderByField[fields.Length];
			for (var i = 0; i < fields.Length; i++)
			{
				Fields[i] = new CamlOrderByField(fields[i]);
			}
		}


		/// <summary>
		/// Initializes a new instance of the <see cref="CamlOrderBy"/> class.
		/// </summary>
		/// <param name="fields">The fields.</param>
		public CamlOrderBy(params CamlOrderByField[] fields)
		{
			Fields = fields;
		}


		/// <summary>
		/// Gets or sets the Fields.
		/// </summary>
		/// <value>The Fields.</value>
		public CamlOrderByField[] Fields { get; set; }


		/// <summary>
		/// Returns a string that represents the current CAML node.
		/// </summary>
		/// <returns>A string representation of the CAML node.</returns>
		public override string ToCaml()
		{
			if (Fields == null || Fields.Length == 0)
				return null;
			
			// build clause
			var camlBuilder = new StringBuilder();
			for (var i = 0; i < Fields.Length; i++)
			{
				camlBuilder.Append(Fields[i].ToCaml());
			}
			return String.Format(CamlFormat, camlBuilder);
		}


		#region | Get Field List |

		/// <summary>
		/// Gets the field list.
		/// </summary>
		/// <param name="fields">The fields.</param>
		/// <returns></returns>
		public static string GetFieldList(params string[] fields)
		{
			return new CamlOrderBy(fields).ToCaml();
		}


		/// <summary>
		/// Gets the field list.
		/// </summary>
		/// <param name="fields">The fields.</param>
		/// <returns></returns>
		public static string GetFieldList(params CamlOrderByField[] fields)
		{
			return new CamlOrderBy(fields).ToCaml();
		}

		#endregion
	}
}
